package com.example.demo.leetcode.top100;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _53课程表
 * @description
 * @date 2023/06/19 21:34
 * <p>
 * ******************************************************
 */
public class _53课程表 {

    public boolean canFinish(int numCourses, int[][] prerequisites) {
        // 构建邻接表
        List<Integer>[] graph = buildGraph(numCourses, prerequisites);

        int[] inDegree = new int[numCourses];
        for (int[] prerequisite : prerequisites) {
            int from = prerequisite[1];
            int to = prerequisite[0];
            inDegree[to]++;
        }

        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < inDegree.length; i++) {
            if (inDegree[i] == 0) {
                queue.offer(i);
            }
        }

        int count = 0;
        while (!queue.isEmpty()) {
            Integer curr = queue.poll();
            count++;
            for (Integer item : graph[curr]) {
                inDegree[item]--;
                if (inDegree[item] == 0) {
                    queue.offer(item);
                }
            }
        }

        return count == numCourses;
    }

    private List<Integer>[] buildGraph(int numCourses, int[][] prerequisites) {
        // 按题意生成邻接表
        // 图中共有 numCourses 个节点
        List<Integer>[] graph = new LinkedList[numCourses];
        for (int i = 0; i < numCourses; i++) {
            graph[i] = new LinkedList<>();
        }
        for (int[] prerequisite : prerequisites) {
            int to = prerequisite[0];
            int from = prerequisite[0];
            graph[from].add(to);
        }
        return graph;
    }
}
